import sys
import os
import shutil
import pytesseract
import time
import json
import hashlib
from PIL import Image, ImageGrab
from PyQt5.QtWidgets import (QApplication, QSystemTrayIcon, QMenu, 
                            QWidget, QVBoxLayout, QPushButton, QLabel, 
                            QTextEdit, QFileDialog, QMessageBox, 
                            QGraphicsDropShadowEffect)
from PyQt5.QtGui import (QIcon, QPixmap, QPainter, QPen, QColor)
from PyQt5.QtCore import Qt, QSize
import requests


class FloatingWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        self.drag_pos = None
        
        # 添加柔和的窗口阴影效果
        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(10)  # 减少模糊半径
        self.shadow.setXOffset(2)
        self.shadow.setYOffset(2)
        self.shadow.setColor(QColor(0, 0, 0, 80))  # 半透明黑色
        self.setGraphicsEffect(self.shadow)
        
        # 设置圆角样式
        self.setStyleSheet("""
            QWidget {
                background-color: white;
                border-radius: 10px;
            }
            QPushButton {
                border-radius: 20px;
                background-color: #f0f0f0;
            }
            QPushButton:hover {
                background-color: #e0e0e0;
            }
        """)

    def paintEvent(self, event):
        """绘制圆角窗口"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(QColor(255, 255, 255))
        painter.setPen(Qt.NoPen)
        painter.drawRoundedRect(self.rect(), 10, 10)

    def initUI(self):
        self.setFixedSize(60, 60)  # 初始大小只容纳主按钮
        self.is_expanded = False
        
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(5)

        # 主菜单按钮
        self.main_button = QPushButton("⚙", self)
        self.main_button.setFixedSize(40, 40)
        self.main_button.clicked.connect(self.toggle_menu)
        
        # 功能按钮 (初始隐藏)
        self.btn_screenshot = QPushButton("📷", self)
        self.btn_screenshot.setFixedSize(40, 40)
        self.btn_screenshot.clicked.connect(self.take_screenshot)
        self.btn_screenshot.hide()

        self.btn_translate = QPushButton("🔤", self)
        self.btn_translate.setFixedSize(40, 40)
        self.btn_translate.clicked.connect(self.show_translate_window)
        self.btn_translate.hide()

        self.btn_clean = QPushButton("🧹", self)
        self.btn_clean.setFixedSize(40, 40)
        self.btn_clean.clicked.connect(self.clean_c_drive)
        self.btn_clean.hide()

        self.btn_close = QPushButton("✖", self)
        self.btn_close.setFixedSize(40, 40)
        self.btn_close.clicked.connect(self.close)
        self.btn_close.hide()

        layout.addWidget(self.main_button)
        layout.addWidget(self.btn_screenshot)
        layout.addWidget(self.btn_translate)
        layout.addWidget(self.btn_clean)
        layout.addWidget(self.btn_close)
        layout.setAlignment(Qt.AlignCenter)
        self.setLayout(layout)

    def toggle_menu(self):
        """切换菜单展开/折叠状态"""
        self.is_expanded = not self.is_expanded
        
        if self.is_expanded:
            self.setFixedSize(60, 180)  # 展开后的大小
            self.btn_screenshot.show()
            self.btn_translate.show()
            self.btn_clean.show()
            self.btn_close.show()
        else:
            self.setFixedSize(60, 60)  # 折叠后的大小
            self.btn_screenshot.hide()
            self.btn_translate.hide()
            self.btn_clean.hide()
            self.btn_close.hide()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            # 左键拖动窗口
            self.drag_pos = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()
        elif event.button() == Qt.RightButton and self.btn_screenshot.underMouse():
            # 右键点击截图按钮时自动保存
            self.take_screenshot(auto_save=True)
        elif event.button() == Qt.RightButton:
            # 右键点击窗口其他位置关闭窗口
            self.close()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton and hasattr(self, 'drag_pos') and self.drag_pos:
            self.move(event.globalPos() - self.drag_pos)
            event.accept()

    def take_screenshot(self, auto_save=False):
        # 隐藏悬浮窗临时
        self.hide()
        QApplication.processEvents()

        # 截取全屏
        screenshot = ImageGrab.grab()
        
        if auto_save:
            # 自动保存到桌面
            desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
            timestamp = time.strftime("%Y%m%d_%H%M%S")
            filename = f"screenshot_{timestamp}.png"
            save_path = os.path.join(desktop, filename)
            screenshot.save(save_path)
            QMessageBox.information(self, "成功", f"截图已自动保存到桌面: {filename}")
        else:
            # 手动选择保存位置
            save_path, _ = QFileDialog.getSaveFileName(
                self, "保存截图", "", "PNG Image (*.png)")
            if save_path:
                screenshot.save(save_path)
                QMessageBox.information(self, "成功", f"截图已保存到: {save_path}")

        self.show()

    def show_translate_window(self):
        self.translate_win = TranslateWindow()
        self.translate_win.show()

    def clean_c_drive(self):
        # 清理临时文件（需要管理员权限）
        temp_paths = [
            "C:/Windows/Temp",
            "C:/Users/{}/AppData/Local/Temp".format(os.environ['USERNAME']),
            "C:/Windows/Prefetch"
        ]
        
        deleted_files = 0
        deleted_size = 0
        errors = 0
        
        try:
            for temp_path in temp_paths:
                if not os.path.exists(temp_path):
                    continue
                    
                for filename in os.listdir(temp_path):
                    file_path = os.path.join(temp_path, filename)
                    try:
                        if os.path.isfile(file_path):
                            deleted_size += os.path.getsize(file_path)
                            os.unlink(file_path)
                            deleted_files += 1
                        elif os.path.isdir(file_path):
                            shutil.rmtree(file_path)
                            deleted_files += 1
                    except Exception as e:
                        errors += 1
                        print(f"无法删除 {file_path}: {e}")

            if deleted_files > 0:
                freed_space = deleted_size / (1024 * 1024)  # 转换为MB
                msg = f"成功清理 {deleted_files} 个临时文件\n释放空间: {freed_space:.2f} MB"
                if errors > 0:
                    msg += f"\n(有 {errors} 个文件/目录无法删除)"
                QMessageBox.information(self, "清理完成", msg)
            else:
                QMessageBox.information(self, "清理完成", "没有找到可清理的临时文件")
                
        except PermissionError:
            QMessageBox.warning(self, "权限不足", 
                "需要以管理员权限运行才能清理系统文件！\n"
                "请右键点击程序图标，选择'以管理员身份运行'")


class TranslateWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("英文翻译器")
        self.setFixedSize(400, 300)
        layout = QVBoxLayout()

        self.input_text = QTextEdit()
        self.input_text.setPlaceholderText("输入要翻译的英文...")
        
        self.btn_translate = QPushButton("翻译")
        self.btn_translate.clicked.connect(self.translate_text)

        self.output_text = QTextEdit()
        self.output_text.setReadOnly(True)

        self.btn_close = QPushButton("关闭")
        self.btn_close.clicked.connect(self.close)

        layout.addWidget(QLabel("输入文本:"))
        layout.addWidget(self.input_text)
        layout.addWidget(self.btn_translate)
        layout.addWidget(QLabel("翻译结果:"))
        layout.addWidget(self.output_text)
        layout.addWidget(self.btn_close)
        self.setLayout(layout)

    def translate_text(self):
        text = self.input_text.toPlainText().strip()
        if not text:
            QMessageBox.warning(self, "警告", "请输入要翻译的文本")
            return
            
        # 尝试使用本地缓存
        cache_file = os.path.join(os.path.dirname(__file__), "translations.json")
        translations = {}
        if os.path.exists(cache_file):
            try:
                with open(cache_file, 'r', encoding='utf-8') as f:
                    translations = json.load(f)
                if text in translations:
                    self.output_text.setText(translations[text])
                    return
            except Exception as e:
                print(f"读取缓存失败: {e}")
                
        # 使用百度翻译API - 请替换为您自己的API密钥
        url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
        appid = "appid"  # 替换为您的百度翻译API appid
        secret = "secret"  # 替换为您的百度翻译API密钥
        salt = str(time.time())
        sign = hashlib.md5((appid + text + salt + secret).encode()).hexdigest()
        
        params = {
            "q": text,
            "from": "en",
            "to": "zh",
            "appid": appid,
            "salt": salt,
            "sign": sign
        }
        
        try:
            response = requests.get(url, params=params, timeout=10)
            response.raise_for_status()
            result = response.json()
            
            if "trans_result" in result:
                translated = result["trans_result"][0]["dst"]
                self.output_text.setText(translated)
                
                # 缓存结果
                translations[text] = translated
                try:
                    with open(cache_file, 'w', encoding='utf-8') as f:
                        json.dump(translations, f, ensure_ascii=False, indent=2)
                except Exception as e:
                    print(f"保存缓存失败: {e}")
                    
            elif "error_code" in result:
                error_msg = {
                    "52001": "请求超时",
                    "52002": "系统错误",
                    "52003": "未授权用户",
                    "54000": "必填参数为空",
                    "54001": "签名错误",
                    "54003": "访问频率受限",
                    "54004": "账户余额不足",
                    "54005": "长query请求频繁",
                    "58000": "客户端IP非法",
                    "58001": "译文语言方向不支持",
                    "58002": "服务当前已关闭",
                    "90107": "认证未通过或未生效"
                }.get(str(result["error_code"]), result.get("error_msg", "未知错误"))
                self.output_text.setText(f"翻译失败: {error_msg}")
            else:
                self.output_text.setText("翻译失败: 未知错误")
                
        except requests.exceptions.RequestException as e:
            self.output_text.setText(f"网络请求失败: {str(e)}")
        except json.JSONDecodeError as e:
            self.output_text.setText(f"解析翻译结果失败: {str(e)}")
        except Exception as e:
            self.output_text.setText(f"翻译处理失败: {str(e)}")


class SystemTrayIcon(QSystemTrayIcon):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setIcon(QIcon("icon.png"))  # 准备一个图标文件
        self.setToolTip("多功能工具箱")
        
        self.menu = QMenu()
        self.menu.addAction("显示悬浮窗", self.show_floating_window)
        self.menu.addAction("退出", self.exit_app)
        self.setContextMenu(self.menu)

        self.floating_window = FloatingWindow()

    def show_floating_window(self):
        self.floating_window.show()

    def exit_app(self):
        self.floating_window.close()
        QApplication.quit()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)

    # 检查Tesseract OCR路径（截图文字识别用）
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # 修改为你的路径

    tray = SystemTrayIcon()
    tray.show()
    tray.show_floating_window()  # 默认启动时显示悬浮窗

    sys.exit(app.exec_())
